package com.siberhus.tdfl;

import org.springframework.core.io.Resource;
import org.springframework.util.Assert;

public abstract class AbstractDataFileWriter implements DataFileWriter {
	
	protected Resource resource;
	
	protected int linesWritten = 0;
	
	protected boolean shouldDeleteIfEmpty = true;
	
	@Override
	public void setResource(Resource resource) {
		this.resource = resource;
	}
	
	public void setShouldDeleteIfEmpty(boolean shouldDeleteIfEmpty) {
		this.shouldDeleteIfEmpty = shouldDeleteIfEmpty;
	}
	
	@Override
	public int getLinesWritten(){
		return linesWritten;
	}
	
	@Override
	public void open(DataContext dataContext) throws Exception {
		Assert.notNull(resource, "The resource must be set");
		doOpen();
	}
	
	@Override
	public void close() throws Exception {
		
		if(!isOpen()) return;
		try{
			doClose();
			
			if (shouldDeleteIfEmpty && linesWritten == 0) {
				if(resource.exists()){
					resource.getFile().delete();
				}
			}
		}finally{
			//reset
			linesWritten = 0;
		}
	}
	
	@Override
	public void update(DataContext dataContext) {
		//nothing for now
	}
	
	@Override
	public void writeLabels(String[] labels) throws Exception {
		doWrite(labels);
	}
	
	@Override
	public void write(String[] values) throws Exception {

		doWrite(values);
		linesWritten++;
	}
	
	protected abstract void doOpen() throws Exception ;
	
	protected abstract void doWrite(String[] values) throws Exception ;
	
	protected abstract void doClose() throws Exception ;
	
}
